package ic.doc.co2nudge.client.utils;

import com.google.gwt.i18n.client.NumberFormat;

import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.user.client.ui.TextBox;

public class Utils {
	
	public static Double getDistanceInKm(Double d){
		return roundWithTwoDecimals(d/1000);
	}
	
	public static Double roundWithTwoDecimals(Double d){
		//NumberFormat f = NumberFormat.getDecimalFormat();
		return d;	//Double.valueOf(f.format(d));
	}
	
	public static Double round(Double d){
		NumberFormat f=NumberFormat.getFormat("#.##");	
		return Double.valueOf(f.format(d));
	}
	
	public static Double getPercentageOfNum(int source, int part){
		return (double)(part/source)*100;
	}
	
	public static Double calcCO2EmissionsBorder(double e, int percentage){
		return Utils.round(e-(e/10));
	}

	public static KeyPressHandler getOnlyNumbersKeyboardAdapter(){
		
		KeyPressHandler onlyNumbersKeyPressHandler=
			new KeyPressHandler(){

				@Override
				public void onKeyPress(KeyPressEvent e) {
					// TODO Auto-generated method stub
					
					char inputChar=e.getCharCode();
					
					if (!Character.isDigit(inputChar)) {
						((TextBox)e.getSource()).cancelKey();
					}
				}
		};
		
		return onlyNumbersKeyPressHandler;
	}
	
	public static KeyPressHandler getDateKeyboardAdapter(){
		
		KeyPressHandler dateKeyPressHandler=
			new KeyPressHandler(){

				@Override
				public void onKeyPress(KeyPressEvent e) {
					// TODO Auto-generated method stub
					
					char inputChar=e.getCharCode();
					
					if (!Character.isDigit(inputChar)
							&&(inputChar!=47)) {
						((TextBox)e.getSource()).cancelKey();
					}
				}
		};
		
		return dateKeyPressHandler;
	}
}
